package com.spzx.common.rabbit.service;

import com.alibaba.fastjson2.JSON;
import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.common.rabbit.entity.GuiguCorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RabbitService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息
     *
     * @param exchange   交换机
     * @param routingKey 路由键
     * @param message    消息
     */
    public boolean sendMessage(String exchange, String routingKey, Object message) {
        GuiguCorrelationData guiguCorrelationData = new GuiguCorrelationData();
        String uuid = UUID.randomUUID().toString().replace("-","");
        guiguCorrelationData.setId(uuid);
        guiguCorrelationData.setExchange(exchange);
        guiguCorrelationData.setRoutingKey(routingKey);
        guiguCorrelationData.setMessage(message);

        // 缓存redis ，防止消息重新发送时，可以从redis获取
        redisTemplate.opsForValue().set(uuid, guiguCorrelationData,10, TimeUnit.MINUTES);
        rabbitTemplate.convertAndSend(exchange, routingKey, message);
        return true;
    }

    /**
     * 发送延时消息
     * @param exchangeDelay
     * @param routingDelay
     * @param msg
     * @param delayTime
     */
    public Boolean sendDealyMessage(String exchangeDelay, String routingDelay, String msg, int delayTime) {

        GuiguCorrelationData guiguCorrelationData = new GuiguCorrelationData();
        String uuid = UUID.randomUUID().toString().replace("-","");
        guiguCorrelationData.setId(uuid);
        guiguCorrelationData.setExchange(exchangeDelay);
        guiguCorrelationData.setMessage(msg);
        guiguCorrelationData.setRoutingKey(routingDelay);
        guiguCorrelationData.setDelay(true);
        guiguCorrelationData.setDelayTime(delayTime);

        redisTemplate.opsForValue().set(uuid, guiguCorrelationData);
        rabbitTemplate.convertAndSend(exchangeDelay, routingDelay, msg,message ->{
            message.getMessageProperties().setDelay(delayTime*1000);
            return message;
        },guiguCorrelationData);
        return true;
    }
}